<template>
  <div class="page-box">
    <div class="page">
      <div class="select-box">
        <div class="create-page-top" v-if="!isSubmit">
          <div>
            <img class="pay-icon" src="@/assets/images/order-pay.png" alt="确认支付">
          </div>
          <div class="order-info">
            <h3>订单确认</h3>
            <el-divider/>
            <div style="display: flex;">
              <div class="order-goods-box">
                <div v-for="(item,index) in payData" :key="index">
                  <div class="item-box">
                    <div class="item-name">
                      <el-image :src="item.goods.cover_pic" style="border-radius: 4px;"></el-image>
                      <div>{{ item.goods.name }}</div>
                    </div>

                    <div class="item-num" v-if="payData[0].shop_type ==1">视频：{{ item.num }}条</div>
                    <div class="item-price">{{ item.goods.price }} $ <span v-if="payData[0].shop_type ==1">/条</span></div>
                  </div>
                </div>
              </div>
              <div class="order-form-box" v-if="payData[0].shop_type == 1">
                <el-form :model="formData" label-width="100" style="max-width: 600px" :rules="rules">
                  <el-form-item label="联系方式" prop="mobile">
                    <el-input v-model="formData.mobile" maxlength="11" autofocus placeholder="请输入联系人手机号"/>
                  </el-form-item>
                  <el-form-item label="需求描述" prop="desc">
                    <el-input v-model="formData.desc" maxlength="60" placeholder="请输入拍摄需求" type="textarea"/>
                  </el-form-item>
                </el-form>
              </div>
            </div>

          </div>
        </div>
        <div class="create-page-top" v-else-if="isSubmit">
          <div>
            <img class="pay-icon" src="@/assets/images/order-pay.png" alt="确认支付">
          </div>
          <div class="order-info">
            <h3>订单提交成功，请尽快付款！</h3>
            <div class="order-num">订单号：{{ wxConfig.out_trade_no }}</div>
            <el-divider/>
            <div>
              <h4>订单结算</h4>
              <div class="jiesuan-box">
                <div>
                  订单金额：<span>{{ wxConfig.total_pay_source }} USD</span>
                </div>
                <div>
                  实时汇率：<span>{{ wxConfig.change_rate }}</span>
                </div>
                <div>
                  支付金额：<span>{{ pageData.total_price }}CNY</span>
                </div>
              </div>
            </div>
          </div>
        </div>


      </div>

      <!--列表-->
      <div class="list-box">
        <div class="create-page-bottom">
          <h4>请选择支付方式</h4>
          <div>
            <el-radio-group v-model="payType" size="large">
              <el-radio-button label="套餐余额" :value="0" v-if="payData[0].shop_type != 2 && userIntegral>totalNum">
                套餐余额{{ userIntegral }}
              </el-radio-button>
              <el-radio-button label="微信支付" :value="1">微信支付</el-radio-button>
              <el-radio-button label="支付宝支付" :disabled="true" :value="2">支付宝支付</el-radio-button>
            </el-radio-group>
          </div>
          <div class="all-money" v-if="payType!=0">
            总计
            <span class="total-box"> {{ pageData.total_price }} </span>
            CNY
          </div>
          <div class="all-money" v-else>
            总计消耗套餐
            <span class="total-box"> {{ totalNum }} </span>
            条
          </div>
          <el-button @click="openPay()" type="primary" round size="large" style="width: 120px">立即支付</el-button>
        </div>
      </div>
    </div>
  </div>

  <el-dialog
      v-model="dialogVisible"
      title="微信扫码支付"
      width="450"
  >
    <div class="disabled-box">
      <div class="code-img-box">
        <wxPay :code_url="wxConfig.code_url"></wxPay>
      </div>

      <div class="disabled-box-title">
        <h3>手机 微信 扫码支付</h3>
        <div style="color: #e6a23c;">
          <span style="font-size: 26px">{{ pageData.total_price }}</span>
          CNY
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import Https from "@/server";
import {onMounted, ref, reactive} from "vue";
import {ElLoading, ElMessage, FormRules} from "element-plus";
import wxPay from "@/components/wxPay.vue";
import {useRouter,useRoute} from "vue-router";

const Router = useRouter();
const Route = useRoute();

interface GoodsItem {
  id: number;
  attrs: Array<{ attr_id: number; attr_group_id: number }>;
  send_type: Array<string>;
  cover: string;
  price: string;
  num: number;
  cat_id: number;
  goods_attr_id: number;
  cart_id: number;
}

interface ParamsType {
  list: Array<{
    goods_list: GoodsItem[];
    mch_id: number;
    distance: number;
    use_integral: number;
    user_coupon_id: number;

    remark: string;
    order_form: [],
  }>;
  address_id: number;
  send_type: string;
  address: {
    name: string;
    mobile: string;
  }
}

interface RuleForm {
  mobile: string
  desc: string
}

const formData = reactive<RuleForm>({
  mobile: '',
  desc: '',
})

const rules = reactive<FormRules<RuleForm>>({
  mobile: [
    {required: true, message: '请输入联系人手机号', trigger: 'blur'},
  ],
  desc: [
    {required: true, message: '请输入拍摄需求', trigger: 'blur'},
  ],
})


const payData = ref([
  {goods: {cover_pic: "", name: "", price: 0}, num: 1, shop_type: 1},
])
const payType = ref(1);
const dialogVisible = ref(false)
const isSubmit = ref(false)
const totalNum = ref(0);
const userIntegral = ref(0);
const orderData = ref("");
const pageData = ref({
  total_price: 0.00
});

// 支付按钮
const openPay = () => {
  if( payData.value[0].shop_type == 1){
    const mobileRegex = /^1[3-9]\d{9}$/;
    if (!mobileRegex.test(formData.mobile)) {
      ElMessage.warning("请输入正确的联系手机号")
      return false;
    }
    if (!formData.desc) {
      ElMessage.warning("请输入拍摄需求");
      return false;
    }
  } else {
    formData.mobile = JSON.parse(localStorage.getItem("userInfo") as string).nickname;
    formData.desc = "购买会员"
  }

  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  setTimeout(() => {
    loading.close()
  }, 2000)
  let params = JSON.parse(orderData.value);
  params.address.name = formData.desc;
  params.address.mobile = formData.mobile;
  params = JSON.stringify(params);
  orderSubmit(params);
}

const orderSubmit = (data: any) => {
  let type = payData.value[0].shop_type ? payData.value[0].shop_type : 1;
  Https.postOrderSubmit(data, type).then((res: any) => {
    if (res.code == 0) {
      orderPayData(res.data);
    }
  })
}

const orderPayData = (data: any) => {
  Https.postPayData(data).then((res: any) => {
    if (res.code === 0) {
      if (res.data.retry) {
        const timeFn = (data: any) => {
          orderPayData(data);
        }
        let ct = setTimeout(() => {
          timeFn(data)
          clearTimeout(ct);
        }, 1000)
      } else {
        getTotalPayment(res.data.id)
      }
    } else {
      ElMessage.error(res.msg);
    }
  })
}

const wxConfig = ref({
  code_url: '',
  out_trade_no: '',
  change_rate: "",
  total_pay_source: "",
})
const paymentData = (data: any) => {
  let params = {
    id: data.id,
    type: data.type,
  }
  Https.getPaymentPayData(params).then((res: any) => {
    if (res.code === 0) {
      if (data.type == "wechat_h5") {
        isSubmit.value = true;
        wxConfig.value = res.data;
        dialogVisible.value = true;
        orderStatus(data.id);
      } else {
        Https.getPaymentBuyBalance(data.id).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success("支付成功")
            Router.push({path: '/order'});
          }
        })
      }

    }
  })
}

const getTotalPayment = (id: number) => {
  Https.getPaymentTotal(id).then((res: any) => {
    if (res.code === 0) {
      if (res.data.amount == 0) {
        let data = {
          id: id,
          type: "balance"
        }
        paymentData(data)

      } else {
        let data = {
          id: id,
          type: "wechat_h5"
        }
        paymentData(data)
      }
    }
    console.log(res);
  })
}

const orderStatus = (id: any) => {
  Https.getOrderStatus(id).then((res: any) => {
    if (res.data.status === 0 && dialogVisible.value == true) {
      let ct = setTimeout(() => {
        orderStatus(id)
        clearTimeout(ct);
      }, 3000)
    } else if (res.data.status === 1) {
      ElMessage.success("支付成功")
      dialogVisible.value = false;
      Router.push({path: '/order'});
    } else if (res.data.status === 0 && !dialogVisible.value) {
      ElMessage.success("取消支付")
    }
  })
}

const userWallet = () => {
  Https.getWebConfig({}).then((res: any) => {
    if (res.code === 0) {
      userIntegral.value = res.data.user_info.options.integral ? res.data.user_info.options.integral : "暂无余额"
    }
  })
}

const orderPreview = ()=>{
  Https.getOrderPreview(orderData.value).then((res: any) => {
    if (res.code == 0) {
      pageData.value = res.data;
    }
  })
}

onMounted(() => {
  userWallet();
  payType.value = Number(Route.query.payType);
  payData.value = JSON.parse(sessionStorage.getItem("orderData") as string);
  if(payData.value[0].shop_type == 2){
    payType.value = 1
  } else {
    payData.value[0].shop_type = 1
  }
  payData.value.forEach(item => {
    totalNum.value += item.num;
  })
  let params: ParamsType = {
    "list": [{
      "mch_id": 0,
      "goods_list": [],
      "distance": 0,
      "remark": "",
      "order_form": [],
      "use_integral": 0,
      "user_coupon_id": 0
    }], "address_id": 0, "send_type": "", "address": {"name": "", "mobile": ""}
  }
  payData.value.forEach((item: any) => {
    let data: GoodsItem = {
      "id": item.goods.id,
      "attrs": [{"attr_id": 2, "attr_group_id": 1}],
      "send_type": ["offline"],
      "price": item.goods.price,
      "cover": item.goods.cover_pic,
      "num": item.num,
      "cat_id": 0,
      "goods_attr_id": item.goods.id,
      "cart_id": item.id ? item.id : 0
    }
    params.list[0].use_integral = payType.value == 1 ? 0 : 1;
    params.list[0].goods_list.push(data);
  });
  orderData.value = JSON.stringify(params);
  orderPreview();
})
</script>
<style scoped lang="scss">
.page-box {
  height: 100%;

  .page {
    padding: 0 20px;
    position: relative;
    box-sizing: border-box;
    height: calc(100% - 60px);
    overflow-y: auto;
    background-color: transparent;
    color: var(--text-color);
  }
}

.create-page-top {
  margin: 35px 45px;
  display: flex;
}

.pay-icon {
  width: 80px;
  height: 80px;
}

.item-box {
  display: flex;
  align-items: center;
  height: 60px;
  width: 500px;
  border-bottom: 1px solid var(--el-color-primary-light-8);

  .item-name {
    flex: 1;
    display: flex;
    align-items: center;

    div {
      max-width: calc(100% - 50px);
      overflow: hidden;
    }
  }

  .item-num {
    width: 100px;
  }

  .item-price {
    width: 120px;
    text-align: right;
  }

  .el-image {
    width: 40px;
    height: 40px;
    margin-right: 10px;
  }
}

.order-info {
  margin: 10px 0 0 22px;
  flex: 1;

  h3 {
    font-size: 24px;
    font-weight: 600;
    padding: 0;
    margin: 0;
  }

  .order-num {
    padding-top: 4px;
    font-size: 14px;
  }

}

.list-box {
  padding: 0 20px 20px;
  background-color: #fff;
  width: 100%;
  border-radius: 0 0 14px 14px;
  display: flex;
  flex-wrap: wrap;

  .el-radio-button {
    margin-right: 10px;
  }
}

.create-page-bottom {
  padding: 41px 166px 41px 160px;
  margin-top: 27px;

  h4 {
    font-size: 22px;
    margin: 0;
    padding-bottom: 10px;
  }

  .all-money {
    margin-top: 30px;
    text-align: left;
    font-size: 18px;
    margin-bottom: 30px;

    span {
      font-size: 30px;
      font-weight: 600;
      color: #09172f;
    }
  }
}

.jiesuan-box {
  max-width: 50vw;
  background: #f1f4fb;
  border-radius: 14px;
  padding: 14px;

  div {
    height: 30px;
    color: #7f7f7f;

    span {
      color: #09172F;
    }
  }
}

.order-goods-box {
  padding-right: 20px;
  border-right: 1px solid rgb(227, 226, 226);
}

.order-form-box {
  padding: 0 20px;
  width: 500px;
}

.disabled-box {
  display: flex;
  align-items: center;
  justify-content: center;

  .code-img-box {
    width: 180px;
    height: 180px;
  }

  .disabled-box-title {
    padding-left: 20px;
  }
}


</style>